package com.atguigu.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.srb.oss.service.FileService;
import com.atguigu.srb.oss.util.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author lwm1435@163.com
 * @date 2022-02-12 11:49
 * @description
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {
    //上传图片，并返回图片在服务器的url
    @Override
    public String upload(InputStream inputStream, String module, String fileName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);

        //判断Bucket是否存在
        String bucketName = OssProperties.BUCKET_NAME;
        if (!ossClient.doesBucketExist(bucketName)) {
            //创建Bucket并设置公开读的权限
            ossClient.createBucket(bucketName);
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        }

        //创建文件目录的结构:"module/2022/01/01/uuid.jpg"
        String filePath = new DateTime().toString("/yyyy/MM/dd/");
        fileName = UUID.randomUUID().toString().replaceAll("-", "")
                + fileName.substring(fileName.lastIndexOf("."));
        filePath = module + filePath + fileName;

        //发送文件对象
        ossClient.putObject(bucketName, filePath, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        //阿里云图片url地址为:https:// "bucketname" . "endpoint" / "filePath"

        return "https://" + bucketName + "." + OssProperties.ENDPOINT + "/" + filePath;
    }

    //删除OSS文件
    @Override
    public void removeFile(String url) {
        // 创建OSSClient实例。
        String endpoint = OssProperties.ENDPOINT;
        OSS ossClient = new OSSClientBuilder().build(
                endpoint,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);
        //截取url中的文件路径  "module/yyyy/MM/dd/uuid.jpg" 为要删除的object
        //即 截掉url前面的路径即可
        String bucketName = OssProperties.BUCKET_NAME;
        String host = "https://" + bucketName + "." + endpoint + "/";
        String objectKey = url.substring(host.length());

        //删除文件
        ossClient.deleteObject(bucketName,objectKey);

        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
